import time
import webbrowser
import threading
from flask import Flask, render_template, request, jsonify
from AppxUtil import *

app = Flask(__name__)


def run_app():
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=False)


@app.route("/")
def index():
    print("打开主页")
    appxs = get_appxs()
    recom = [app for app in appxs if app.name in recom_uninstall_list]
    frameworks = [app for app in appxs if app.is_framework]
    other_uninstallable = [app for app in appxs if (app not in recom and app.canbe_uninstall and app not in frameworks)]

    return render_template("index.html", appxs=appxs, recom=recom, frameworks=frameworks,
                           other_uninstallable=other_uninstallable)


@app.route("/uninstall", methods=['POST'])
def uninstall():
    name = request.form.get('name')  # 获取name参数
    print(f"接收到的卸载请求: {name}")
    result = {"code": 0, "message": "卸载成功"}  # 默认成功

    try:
        apps = get_appxs()
        app_to_uninstall = next((app for app in apps if app.name == name), None)
        if app_to_uninstall:
            app_to_uninstall.uninstall()
        else:
            result["code"] = -1
            result["message"] = "未找到对应的应用"
    except Exception as e:
        result["code"] = -1
        result["message"] = f"卸载失败: {str(e)}"

    return jsonify(result)  # 返回JSON格式的结果


@app.route("/onekey_uninstall", methods=['POST'])
def onekey_uninstall():
    names = request.form.getlist('names[]')
    print("接收到的卸载列表:", names)
    result = {"code": 0, "message": "卸载成功"}  # 默认成功

    try:
        apps = get_appxs()
        for x in apps:
            if x.name in names:
                x.uninstall()
    except Exception as e:
        result["code"] = -1
        result["message"] = f"卸载失败: {str(e)}"

    return jsonify(result)  # 返回JSON格式的结果


def start_app():
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=False)


def browser_open():
    print("打开浏览器")
    time.sleep(0.2)
    webbrowser.open("http://127.0.0.1:5000/")


threading.Thread(target=run_app).start()
threading.Thread(target=browser_open).start()
